<?php
/**
 * [WeEngine System] Copyright (c) 2014 WE7.CC
 * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
 */
defined('IN_IA') or exit('Access Denied');

$dos = array('get_setting', 'display', 'save_setting');
$do = in_array($do, $dos) ? $do : 'display';
permission_check_account_user('wxapp_payment_pay');

$setting = uni_setting_load('payment', $_W['uniacid']);
$pay_setting = empty($setting['payment']) ? [] : $setting['payment'];
$wxapp_info = miniapp_fetch($_W['uniacid']);

if (in_array($do, array('get_setting', 'display'))) {
	if (empty($pay_setting['wechat'])) {
		$pay_setting['wechat'] = ['mchid' => '', 'signkey' => ''];
	}
	if (empty($pay_setting['wechat_v3'])) {
		$pay_setting['wechat_v3'] = ['mchid' => '', 'signkey' => ''];
	}
	if (empty($pay_setting['wechat_facilitator'])) {
		$pay_setting['wechat_facilitator'] = ['sub_mch_id' => '', 'service' => ''];
	}
}

if ('get_setting' == $do) {
	iajax(0, $pay_setting, '');
}

if ('display' == $do) {
	
}

if ('save_setting' == $do) {
	$type = safe_gpc_string($_GPC['type']);
	$param = safe_gpc_array($_GPC['param']);
	$setting = uni_setting_load('payment', $_W['uniacid']);
	$pay_setting = empty($setting['payment']) ? array() : $setting['payment'];

	
	if ('wechat' == $type) {
		$param['switch'] = !empty($param['switch']) ? STATUS_ON : STATUS_OFF;
		$param['account'] = $_W['acid'];
		if (!empty($param['switch'])) {
			$pay_setting['wechat_facilitator']['switch'] = STATUS_OFF;
			$pay_setting['wechat_v3']['switch'] = STATUS_OFF;
		}
	}
	if ('wechat_v3' == $type) {
		$param['switch'] = !empty($param['switch']) ? STATUS_ON : STATUS_OFF;
		$param['account'] = $_W['acid'];
		if (!empty($param['switch'])) {
			$pay_setting['wechat_facilitator']['switch'] = STATUS_OFF;
			$pay_setting['wechat']['switch'] = STATUS_OFF;
		}
		if (!empty($param['switch']) && !empty($param['ertificate_serial_number'])) {
			if (strexists($param['apiclient_key'], '<?php') || '-----BEGIN PRIVATE KEY-----' != substr($param['apiclient_key'], 0, 27) || '---END PRIVATE KEY-----' != substr($param['apiclient_key'], -23, 23)) {
				iajax(-1, 'apiclient_key.pem证书内容不合法！');
			}
			load()->library('wechatpay-v3');
			$merchantId = $param['mchid'];
			$merchantSerialNumber = $param['ertificate_serial_number'];
			$merchantPrivateKey = $param['apiclient_key'];

			$wechatpayMiddleware = WechatPay\GuzzleMiddleware\WechatPayMiddleware::builder()
				->withMerchant($merchantId, $merchantSerialNumber, $merchantPrivateKey)
				->withValidator(new WechatPay\GuzzleMiddleware\NoopValidator)
				->build();
			$stack = GuzzleHttp\HandlerStack::create();
			$stack->push($wechatpayMiddleware, 'wechatpay');
			$client = new GuzzleHttp\Client(['handler' => $stack]);
			try {
				$canonical_url = '/v3/certificates';
				$http_method = 'GET';
				$timestamp = time();
				$nonce = random(32);
				$message = $http_method . "\n" . $canonical_url . "\n" . $timestamp . "\n" . $nonce . "\n\n";
				openssl_sign($message, $raw_sign, $merchantPrivateKey, 'sha256WithRSAEncryption');
				$sign = base64_encode($raw_sign);
				$schema = "WECHATPAY2-SHA256-RSA2048";
				$token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $merchantId, $nonce, $timestamp, $merchantSerialNumber, $sign);
				$resp = $client->request('GET', 'https://api.mch.weixin.qq.com/v3/certificates', [
					'headers' => [
						'Authorization' => $schema . ' ' . $token,
						'Accept' => 'application/json',
						'User-Agent' => '用户代理(https://zh.wikipedia.org/wiki/User_agent)',
					]
				]);
				if ($resp->getStatusCode() < 200 || $resp->getStatusCode() > 299) {
					iajax(-1, "download failed, code={$resp->getStatusCode()}, body=[{$resp->getBody()}]");
				}
				$list = json_decode($resp->getBody(), true);
				$plain_certs = [];
				$decrypter = new WechatPay\GuzzleMiddleware\Util\AesUtil($param['signkey']);
				foreach ($list['data'] as $item) {
					$encCert = $item['encrypt_certificate'];
					$plain = $decrypter->decryptToString($encCert['associated_data'], $encCert['nonce'], $encCert['ciphertext']);
					if (empty($plain)) {
						iajax(-1, "微信平台证书解密失败!");
					}
					$plain_certs[] = $plain;
				}
				$param['wechat_platform_certificate'] = $plain_certs;
			} catch (RequestException $e) {
				iajax(-1, $e->getMessage());
			}
		}
	}

	$pay_setting[$type] = $param;
	$payment = iserializer($pay_setting);
	uni_setting_save('payment', $payment);
	iajax(0, '设置成功', url('wxapp/payment', array('version_id' => $version_id)));
}
template('wxapp/payment');
